package com.cloud_sang.fubai.controller;

import com.cloud_sang.entity.CommonResult;
import com.cloud_sang.entity.Payment;
import com.cloud_sang.fubai.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * @ClassTitle: OrderController
 * @ProjectName springcould2020
 * @Description:
 * @Author Sangsang
 * @Date 2020/9/9
 * @Time 18:05
 */
@RestController
@Slf4j
public class OrderController {

	//public static final String PAYMENT_URL = "http://localhost:8001";
	public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";;

	@Resource
	private RestTemplate restTemplate;

	@Resource
	private LoadBalancer loadBalancer;
	@Resource
	private DiscoveryClient discoveryClient;


	@PostMapping("/consumer/payment/create")
	public CommonResult<Payment> create(Payment payment){
		return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommonResult.class);  //写操作
	}

	@GetMapping("/consumer/payment/get/{id}")
	public CommonResult<Payment> getPayment(@PathVariable("id") Long id){
		//http://localhost:80/consumer/payment/get/{id}?id=1
		return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
	}

	@GetMapping("/consumer/payment/getForEntity/{id}")
	public CommonResult<Payment> getForEntity(@PathVariable("id") Long id){
		//http://localhost:80/consumer/payment/get/{id}?id=1
		ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
		if (entity.getStatusCode().is2xxSuccessful()){
			return entity.getBody();
		}
		return new CommonResult(444,"失败!!!");
	}
	@GetMapping("/consumer/payment/lb")
	public String getPaymentLB() {
		// 通过容器中的 discoveryClient和服务名来获取服务集群
		List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
		if(instances == null || instances.size() <= 0) {
			return null;
		}
		// 传入服务集群来计算出获取具体的服务实例
		ServiceInstance serviceInstance = loadBalancer.pollingInstances(instances);
		URI uri = serviceInstance.getUri();
		return  restTemplate.getForObject(uri+"/payment/lb",String.class);
	}


}
